package com.frogs.ucenter.component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.framework.web.HttpResponseUtil;
import com.frogs.system.util.ApplicablePlatformEnum;
import com.frogs.system.util.OpenPlatformEnum;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.entity.UserBaseAccountInfo;
import com.frogs.ucenter.service.UserService;
import com.frogs.ucenter.util.CpsConstant;
import com.frogs.ucenter.util.SysStatusEnum;

@Component("userPermissionHelper")
public class UserPermissionHelper {
	private static final Logger log = LoggerFactory.getLogger(UserPermissionHelper.class);
	private static final int COOKIE_TIME_OUT = 60 * 60 * 24 * 30;
	public static final String COOKIE_UID = "uid";
	public static final String COOKIE_PIC_URL = "picurl";
	public static final String COOKIE_USER_NAME = "username";
	public static final String COOKIE_NICK_NAME = "nickname";
	public static final String COOKIE_DOMAIIN_NAME = "DomainName";
	public static final String COOKIE_VERIFY = "verify";
	public static final String COOKIE_OPENPLATFORM_ID = "openPlatform";
	public static final String COOKIE_DOMAIN = ".frogshealth.com";
	
	@Resource
	private UserService userService;
	@Resource
	private RsyncHelper rsyncHelper;
	
	/**
	 * 注册并登录
	 */
	public Map<String, Object> register(HttpServletRequest request, HttpServletResponse response, String userName, String nickName,
			String passwd, String confirmPasswd, String _wt_pk_cookie, Integer applicablePlatformId) {
		Map<String, Object> object = new HashMap<String, Object>();
		JSONObject result;
		try {
			result = userService.register(userName, nickName, passwd, confirmPasswd, HttpRequestInfo.getUserIp(request), 
					new HttpRequestInfo(request).getCookieValue(CpsConstant.CPS_SOURCE_NAME, ""), applicablePlatformId);
			if (result != null) {
				if (ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
					object.put(ResultParamEnum.code.getParamName(), SysStatusEnum.SUCCESS.getCode());
					UserBaseAccountInfo accountInfo = JSONObject.toJavaObject(result.getJSONObject("response").getJSONObject("info"), UserBaseAccountInfo.class);
					setUserCookie(request, response, accountInfo);
					rsyncHelper.mergeShoppingCart(accountInfo.getId(), _wt_pk_cookie);
				} else {
					object.put(ResultParamEnum.code.getParamName(), SysStatusEnum.FAIL.getCode());
				}
				object.put(ResultParamEnum.tip.getParamName(), result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
				log.error("func[register] tip[{}] desc[register]",
						new Object[] { result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()) });
			}
		} catch (Exception e) {
			log.error("func[register] userName[{}] exception[{} - {}] desc[fail]",//
					new Object[] { userName, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
		return object;
	}
	
	/**
	 * 获取登录用户
	 */
	public UserBaseAccountInfo getUser(HttpServletRequest request) {
		Integer userId = Integer.valueOf(this.getCookieVal(request, COOKIE_UID));
		
		if (userId != null ) {
			UserBaseAccountInfo accountInfo;
			try {
				accountInfo = userService.getUser(userId);
				return accountInfo;
			} catch (Exception e) {
				log.error("func[getUser] userId[{}] exception[{} - {}] desc[fail]",//
						new Object[] { userId, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			}
			
		}
		return null;
	}

	/**
	 * 是否已经登录
	 * 
	 * @param request
	 * @return
	 */
	public Boolean isLogin(HttpServletRequest request) {
		String userId = this.getCookieVal(request, COOKIE_UID);
		String verify = this.getCookieVal(request, COOKIE_VERIFY);
		HttpRequestInfo requestInfo = new HttpRequestInfo(request);
		String userIp = requestInfo.getUserIp();
		if(!StringUtil.isEmpty(userId) && !StringUtil.isEmpty(verify)) {
			try {
				return userService.islogin(Integer.parseInt(userId), userIp);
			} catch (Exception e) {
				log.error("func[isLogin] userId[{}] exception[{} - {}] desc[fail]",//
						new Object[] { userId, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			}
		}
		return Boolean.FALSE;
	}

	/**
	 * 登录
	 * @param request
	 * @param response
	 * @param userName
	 * @param password
	 * @return
	 */
	public Map<String, Object> login(HttpServletRequest request, HttpServletResponse response, String userName, 
			String password, int isphpw, int isKpw, String _wt_pk_cookie) {
		Map<String, Object> object = new HashMap<String, Object>();
		JSONObject result;
		try {
			HttpRequestInfo requestInfo = new HttpRequestInfo(request);
			String ip = requestInfo.getUserIp();
			Integer platform = requestInfo.getIntParameter("platform", ApplicablePlatformEnum.WEB.getId());
			if (isphpw == 1) {
				result = userService.loginByDynamicPassword(userName, password, ip, platform);
			} else {
				result = userService.login(userName, password, ip);
			}
			if (result != null) {
				if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
					object.put(ResultParamEnum.code.getParamName(), SysStatusEnum.FAIL.getCode());
					object.put(ResultParamEnum.tip.getParamName(), result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
					log.error("func[login] tip[{}] desc[register fail]",
							new Object[] { result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()) });
					return object;
				}
				object.put(ResultParamEnum.code.getParamName(), SysStatusEnum.SUCCESS.getCode());
				UserBaseAccountInfo accountInfo = JSONObject.toJavaObject(result.getJSONObject("response").getJSONObject("userBaseAccountInfo"), UserBaseAccountInfo.class);  //result.getJSONObject("response").get("userBaseAccountInfo");
				String verify = accountInfo.getVerify();
				if (isKpw == 1) {
					setUserCookie(request, response, accountInfo);
				} else {
					setUserSession(request, response, accountInfo);
				}
				rsyncHelper.mergeShoppingCart(accountInfo.getId(), _wt_pk_cookie);
				return object;
			}
		} catch (Exception e) {
			log.error("func[login] userName[{}] exception[{} - {}] desc[fail]",//
					new Object[] { userName, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
		
		return null;
	}
	
	/**
	 * 退出
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HttpRequestInfo requestInfo = new HttpRequestInfo(request);
		String uid = this.getCookieVal(request, COOKIE_UID);
		String verify = this.getCookieVal(request, COOKIE_VERIFY);
		log.info("func[logout] uid[" + uid + "]");
		if (uid != null) {
			Integer userId = Integer.parseInt(uid);
			String _wt_pk_cookie = requestInfo.getParameter("_wt_pk_cookie", "");
			//再次合并购物车
			log.info("logout[trace_id="+_wt_pk_cookie+"] [userId="+userId+"]");
			rsyncHelper.mergeShoppingCart(userId, _wt_pk_cookie);
			
			userService.logout(userId);
			
			this.cleanUserCookie(response);
		}
	}

	/**
	 * 设置cookies
	 * @param request
	 * @param response
	 * @param user
	 */
	public void setUserCookie(HttpServletRequest request, HttpServletResponse response, UserBaseAccountInfo user) {
		HttpResponseUtil.setCookie(response, COOKIE_UID, user.getId().toString(), COOKIE_DOMAIN, "/", COOKIE_TIME_OUT);
		HttpResponseUtil.setCookie(response, COOKIE_NICK_NAME, user.getNickName(), COOKIE_DOMAIN, "/", COOKIE_TIME_OUT);
		HttpResponseUtil.setCookie(response, COOKIE_PIC_URL, user.getHeadImageUrl(), COOKIE_DOMAIN, "/", COOKIE_TIME_OUT);
		HttpResponseUtil.setCookie(response, COOKIE_USER_NAME, user.getAccountName(), COOKIE_DOMAIN, "/", COOKIE_TIME_OUT);
		HttpResponseUtil.setCookie(response, COOKIE_VERIFY, user.getVerify(), COOKIE_DOMAIN, "/", COOKIE_TIME_OUT);
	}
	
	/**
	 * 设置cookies 关闭窗口失效
	 * @param request
	 * @param response
	 * @param user
	 */
	public void setUserSession(HttpServletRequest request, HttpServletResponse response, UserBaseAccountInfo user) {
		HttpResponseUtil.setCookie(response, COOKIE_UID, user.getId().toString(), COOKIE_DOMAIN, "/", -1);
		HttpResponseUtil.setCookie(response, COOKIE_NICK_NAME, user.getNickName(), COOKIE_DOMAIN, "/", -1);
		HttpResponseUtil.setCookie(response, COOKIE_PIC_URL, user.getHeadImageUrl(), COOKIE_DOMAIN, "/", -1);
		HttpResponseUtil.setCookie(response, COOKIE_USER_NAME, user.getAccountName(), COOKIE_DOMAIN, "/", -1);
		HttpResponseUtil.setCookie(response, COOKIE_VERIFY, user.getVerify(), COOKIE_DOMAIN, "/", -1);
	}
	
	public void setOpenPlatformCookie(HttpServletRequest request, HttpServletResponse response, UserBaseAccountInfo user, Integer openPlatformId,String openId) {
		setUserCookie(request, response, user);
		if (openPlatformId > 0) {
			HttpResponseUtil.setCookie(response, COOKIE_OPENPLATFORM_ID, openPlatformId.toString(), COOKIE_DOMAIN, "/", COOKIE_TIME_OUT);
			
			//qq登录和彩贝登录 需要记录cookie 用于下订单的时候回传给领克特
			if(openPlatformId == OpenPlatformEnum.QQ.getId() || openPlatformId == OpenPlatformEnum.CAIBEI.getId() ){
				HttpResponseUtil.setCookie(response, CpsConstant.COOKIE_QQ_OPEN_ID, openId, COOKIE_DOMAIN, "/", COOKIE_TIME_OUT);
				HttpResponseUtil.setCookie(response, CpsConstant.CPS_ID, "lkt", COOKIE_DOMAIN, "/",COOKIE_TIME_OUT);
				HttpResponseUtil.setCookie(response, CpsConstant.CPS_SOURCE_NAME, "lkt",COOKIE_DOMAIN, "/",COOKIE_TIME_OUT);
			}
		}
	}

	/**
	 * 清除cookies
	 * 
	 * @param response
	 */
	public void cleanUserCookie(HttpServletResponse response) {
		HttpResponseUtil.setCookie(response, COOKIE_UID, null,COOKIE_DOMAIN, "/", 0);
		HttpResponseUtil.setCookie(response, COOKIE_NICK_NAME, null,COOKIE_DOMAIN, "/", 0);
		HttpResponseUtil.setCookie(response, COOKIE_PIC_URL, null,COOKIE_DOMAIN, "/", 0);
		HttpResponseUtil.setCookie(response, COOKIE_USER_NAME, null,COOKIE_DOMAIN, "/", 0);
		HttpResponseUtil.setCookie(response, COOKIE_VERIFY, null,COOKIE_DOMAIN, "/", 0);
		HttpResponseUtil.setCookie(response, COOKIE_OPENPLATFORM_ID, null,COOKIE_DOMAIN, "/", 0);
	}

	public String getCookieVal(HttpServletRequest request, String cookieName) {
		String cookieVal = "";
		HttpRequestInfo httpRequest = new HttpRequestInfo(request);
		Cookie cookie = httpRequest.getCookie(cookieName);
		if (cookie != null) {
			return cookie.getValue();
		}
		return cookieVal;
	}
}